<template>
  <div class="gift-list">
    <!-- 查询区域 -->
    <el-card class="mb">
      <el-form :model="searchParams" inline>
        <el-form-item label="礼物类型">
          <el-select 
            v-model="searchParams.giftType" 
            placeholder="请选择礼物类型" 
            clearable 
            style="width: 200px;"
          >
            <el-option label="全部" value="" />
            <el-option label="普通礼物" value="ORDINARY" />
            <el-option label="幸运礼物" value="LUCKY" />
            <el-option label="国家礼物" value="NATIONAL" />
          </el-select>
        </el-form-item>
        <el-form-item label="上架状态">
          <el-select 
            v-model="searchParams.enable" 
            placeholder="请选择上架状态" 
            clearable 
            style="width: 200px;"
          >
            <el-option label="已上架" :value="true" />
            <el-option label="未上架" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd" style="margin-left: 10px;">
            <el-icon><Plus /></el-icon>
            新增礼物
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <el-table 
        :data="dataList" 
        v-loading="loading" 
        :fit="true"
        style="width: 100%"
      >
        <el-table-column prop="id" label="礼物ID" min-width="200" show-overflow-tooltip />
        <el-table-column label="中文名称" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.name.zh || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="英文名称" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.name.en || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="阿语名称" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.name.ar || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="礼物图片" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <el-avatar 
              :src="row.previewImageUrl" 
              :size="60" 
              class="gift-avatar"
              @click="handlePreviewImage(row.previewImageUrl, row.name.zh || row.name.en || row.name.ar)"
              style="cursor: pointer;"
            />
          </template>
        </el-table-column>
        <el-table-column label="礼物动效" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="animation-container">
              <div 
                v-if="row.animationImageUrl && row.animationImageUrl.trim() !== ''" 
                class="animation-preview"
                @click="handlePreviewAnimation(row.animationImageUrl, row.name.zh || row.name.en || row.name.ar)"
                style="cursor: pointer;"
              >
                <el-icon><VideoPlay /></el-icon>
                <span>SVGA动效</span>
              </div>
              <div v-else class="no-animation">
                <el-icon><VideoPlay /></el-icon>
                <span>无动效</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="礼物类型" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag :type="getGiftTypeTagType(row.giftType)">
              {{ GIFT_TYPE_MAP[row.giftType] || row.giftType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="价格" min-width="100" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="coin-price">{{ row.coin }} 金币</span>
          </template>
        </el-table-column>
        <el-table-column label="上架状态" min-width="100" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag :type="row.enable ? 'success' : 'danger'">
              {{ row.enable ? '已上架' : '未上架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" min-width="80" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pageInfo.page"
          v-model:page-size="pageInfo.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totals"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 图片预览组件 -->
    <ImagePreview 
      v-model="previewVisible" 
      :image-url="previewImageUrl" 
      :title="previewTitle" 
    />

    <!-- 动效预览对话框 -->
    <el-dialog
      v-model="animationPreviewVisible"
      :title="animationPreviewTitle"
      width="60%"
      :close-on-click-modal="false"
      class="animation-preview-dialog"
    >
      <div class="animation-preview-content">
        <div class="animation-info">
          <p><strong>动效文件：</strong>{{ animationPreviewUrl }}</p>
          <p><strong>文件格式：</strong>SVGA</p>
          <p><strong>说明：</strong>SVGA是一种轻量级的动画格式，点击下方按钮可以下载文件或复制链接</p>
        </div>
        <div class="animation-actions">
          <el-button type="primary" @click="downloadAnimation">
            <el-icon><Download /></el-icon>
            下载动效文件
          </el-button>
          <el-button @click="copyAnimationUrl">
            <el-icon><CopyDocument /></el-icon>
            复制链接
          </el-button>
          <el-button type="success" @click="openAnimationInNewTab">
            <el-icon><Link /></el-icon>
            新窗口打开
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 礼物表单弹框 -->
    <GiftForm
      v-model="giftFormVisible"
      :gift-data="currentGiftData"
      :is-edit="isEditMode"
      @submit="handleGiftSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue"
import { useHttp } from "@/hooks/useHttp"
import { ElMessage } from "element-plus"
import { VideoPlay, Plus, Download, CopyDocument, Link } from "@element-plus/icons-vue"
import ImagePreview from "@/components/ImagePreview.vue"
import GiftForm from "./components/GiftForm.vue"
import { addGiftApi, updateGiftApi, type GiftAddReq, type GiftUpdateReq } from "@/api/gift"





// 礼物类型映射
const GIFT_TYPE_MAP = {
  'ORDINARY': '普通礼物',
  'LUCKY': '幸运礼物',
  'NATIONAL': '国家礼物'
}

// 查询参数类型
interface SearchType {
  giftType: string
  enable: boolean | null
}

// 多语言名称类型
interface MultiLanguageName {
  zh: string
  en: string
  ar: string
  text?: string
}

// 礼物信息类型
interface GiftInfo {
  id: string
  createUser: string | null
  createTime: string
  modifyUser: string | null
  modifyTime: string
  name: MultiLanguageName
  coin: number
  previewImageUrl: string
  animationImageUrl: string
  sort: number
  giftType: string
  desc: MultiLanguageName
  label: string[]
  enable: boolean
}

// 查询参数
const searchParams = ref<SearchType>({
  giftType: "",
  enable: true
})

// 图片预览相关
const previewVisible = ref(false)
const previewImageUrl = ref("")
const previewTitle = ref("")

// 动效预览相关
const animationPreviewVisible = ref(false)
const animationPreviewUrl = ref("")
const animationPreviewTitle = ref("")

// 礼物表单相关
const giftFormVisible = ref(false)
const currentGiftData = ref<any>(null)
const isEditMode = ref(false)

// 使用 useHttp hook 管理数据
const { 
  dataList, 
  loading, 
  totals, 
  pageInfo, 
  loadData, 
  handleSizeChange, 
  handleCurrentChange, 
  resetPagination 
} = useHttp<GiftInfo>("/gift/page", searchParams, {
  pageKey: 'pageNum',
  pageSizeKey: 'pageSize',
  totalKey: 'total',
  listKey: 'list',
  filterEmptyValues: true // 过滤空值参数
})

// 查询方法
const handleSearch = () => {
  resetPagination()
  // resetPagination() 内部已经调用了 loadData()，不需要重复调用
}

// 获取礼物类型标签样式
const getGiftTypeTagType = (giftType: string) => {
  switch (giftType) {
    case 'NATIONAL': // 国家礼物
      return 'danger'
    case 'LUCKY': // 幸运礼物
      return 'warning'
    case 'ORDINARY': // 普通礼物
      return 'info'
    default:
      return ''
  }
}

// 重置方法
const handleReset = () => {
  searchParams.value = {
    giftType: "",
    enable: true
  }
  resetPagination()
  // resetPagination() 内部已经调用了 loadData()，不需要重复调用
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 新增方法
const handleAdd = () => {
  isEditMode.value = false
  currentGiftData.value = null
  giftFormVisible.value = true
}

// 编辑方法
const handleEdit = (row: GiftInfo) => {
  isEditMode.value = true
  currentGiftData.value = { ...row }
  giftFormVisible.value = true
}

// 处理礼物表单提交
const handleGiftSubmit = async (formData: any) => {
  try {
    console.log('开始处理表单提交，编辑模式:', isEditMode.value)
    console.log('表单数据:', formData)
    
    if (isEditMode.value) {
      // 编辑模式 - 使用 GiftUpdateReq
      const updateData: GiftUpdateReq = {
        id: currentGiftData.value.id,
        name: {
          zh: formData.name.zh,
          en: formData.name.en,
          ar: formData.name.ar
        },
        coin: formData.coin,
        previewImageUrl: formData.previewImageUrl,
        animationImageUrl: formData.animationImageUrl || '',
        sort: formData.sort,
        giftType: formData.giftType,
        desc: {
          zh: formData.desc.zh,
          en: formData.desc.en,
          ar: formData.desc.ar
        },
        label: formData.label || [],
        enable: formData.enable
      }
      console.log('编辑数据:', updateData)
      console.log('当前礼物ID:', currentGiftData.value.id)
      
      await updateGiftApi(currentGiftData.value.id, updateData)
      ElMessage.success('编辑成功')
    } else {
      // 新增模式 - 使用 GiftAddReq
      const addData: GiftAddReq = {
        id: formData.id,
        name: {
          zh: formData.name.zh,
          en: formData.name.en,
          ar: formData.name.ar
        },
        coin: formData.coin,
        previewImageUrl: formData.previewImageUrl,
        animationImageUrl: formData.animationImageUrl || '',
        sort: formData.sort,
        giftType: formData.giftType,
        desc: {
          zh: formData.desc.zh,
          en: formData.desc.en,
          ar: formData.desc.ar
        },
        label: formData.label || [],
        enable: formData.enable
      }
      await addGiftApi(addData)
      ElMessage.success('新增成功')
    }
    
    // 关闭弹框
    giftFormVisible.value = false
    
    // 刷新列表
    loadData()
    
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  }
}

// 图片预览方法
const handlePreviewImage = (imageUrl: string, giftName: string) => {
  previewImageUrl.value = imageUrl
  previewTitle.value = `${giftName} - 礼物图片`
  previewVisible.value = true
}

// 动效预览方法
const handlePreviewAnimation = (animationUrl: string, giftName: string) => {
  animationPreviewUrl.value = animationUrl
  animationPreviewTitle.value = `${giftName} - 礼物动效`
  animationPreviewVisible.value = true
}

// 下载动效文件
const downloadAnimation = () => {
  if (animationPreviewUrl.value) {
    const link = document.createElement('a')
    link.href = animationPreviewUrl.value
    link.download = `gift_animation_${Date.now()}.svga`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    ElMessage.success('开始下载动效文件')
  }
}

// 复制动效链接
const copyAnimationUrl = () => {
  if (animationPreviewUrl.value) {
    navigator.clipboard.writeText(animationPreviewUrl.value).then(() => {
      ElMessage.success('动效链接已复制到剪贴板')
    }).catch(() => {
      ElMessage.error('复制失败')
    })
  }
}

// 新窗口打开动效
const openAnimationInNewTab = () => {
  if (animationPreviewUrl.value) {
    window.open(animationPreviewUrl.value, '_blank')
  }
}



// 组件挂载后初始化
onMounted(() => {
  loadData()
})
</script>

<style lang="less" scoped>
.gift-list {
  .mb {
    margin-bottom: 15px;
    
    // 增大查询区域字体
    :deep(.el-form-item__label) {
      font-size: 14px;
      font-weight: 500;
    }
    
    :deep(.el-input__inner) {
      font-size: 14px;
    }
    
    :deep(.el-select) {
      font-size: 14px;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    
    // 增大分页字体
    :deep(.el-pagination) {
      font-size: 14px;
      
      .el-pagination__total {
        font-size: 14px;
      }
      
      .el-pagination__sizes {
        font-size: 14px;
      }
      
      .el-pagination__jump {
        font-size: 14px;
      }
    }
  }

  .gift-avatar {
    border-radius: 4px;
    transition: transform 0.2s;
    
    &:hover {
      transform: scale(1.05);
    }
  }

  .coin-price {
    color: #f56c6c;
    font-weight: 500;
  }



  .animation-container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60px;
  }

  // 增大表格字体
  :deep(.el-table) {
    font-size: 14px;
    
    .el-table__header {
      th {
        font-size: 15px;
        font-weight: 600;
        color: #333;
      }
    }
    
    .el-table__body {
      td {
        font-size: 14px;
        padding: 12px 0;
      }
    }
  }

  // 增大按钮字体
  :deep(.el-button) {
    font-size: 14px;
  }

  // 增大标签字体
  :deep(.el-tag) {
    font-size: 13px;
  }

  // 增大头像尺寸
  :deep(.el-avatar) {
    font-size: 14px;
  }

  .animation-preview {
    width: 60px;
    height: 60px;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
    transition: transform 0.2s;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    gap: 4px;
    
    &:hover {
      transform: scale(1.05);
      border-color: #409eff;
      background-color: #ecf5ff;
    }
    
    .el-icon {
      font-size: 18px;
      color: #409eff;
    }
    
    span {
      font-size: 10px;
      color: #409eff;
      font-weight: 500;
    }
  }

  .no-animation {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
    color: #999;
    font-size: 12px;
    
    .el-icon {
      font-size: 20px;
    }
  }
}

.animation-preview-dialog {
  .animation-preview-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .animation-info {
    background-color: #f5f7fa;
    padding: 20px;
    border-radius: 8px;
    border: 1px solid #e4e7ed;
    
    p {
      margin: 8px 0;
      line-height: 1.6;
      
      strong {
        color: #333;
      }
    }
  }

  .animation-actions {
    display: flex;
    gap: 10px;
    justify-content: center;
  }
}
</style>
